package com.example.safeassistan.train.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;

import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.train.adapter.SimulateAmswerCardAdapter;
import com.example.safeassistan.train.adapter.TestAmswerCardAdapter;
import com.example.safeassistan.train.model.PaperResultModel;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.widget.ExitAnswerProblemDialog1;
import com.example.safeassistan.widget.PastTestDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.List;

/***
 * 模拟答题卡
 * **/

public class ActivitySimulateAnswerCard extends BaseActivity implements View.OnClickListener {
    private TextView tvSubmit, tvMutil,tvJudge;
    private RecyclerView rcMuti,rcSignal,rcJduge;
    private SimulateAmswerCardAdapter singleAdapter,multAdapter,judgeAdapter;
    private List<List<String>> options;//答案列表
    private List<List<String>> myOptions;//对错列表
    private String paperId="";//试卷id
    private int userScore=0;//得分
    private int correctCount=0;//答对数目
    private int paperMark1=0;
    private  int paperMark2=0;
    private int paperMark3=0;
    private String startTime="";//答题开始时间

    private String surplusTime="";//剩余时间

    private int totalScore=0;//试卷总分数
    private int editCount=0;//所答题目数
    private  int totalCount=0;


    public static void actionStart(Context context,List<List<String>> options,List<List<String>>  myOptions,String paperId,
                                   int paperMark1,int paperMark2,int paperMark3,String startTime,String surplusTime) {
        Intent intent = new Intent(context, ActivitySimulateAnswerCard.class);
        intent.putExtra("options",(Serializable) options);
        intent.putExtra("myOptions",(Serializable) myOptions);
        intent.putExtra("paperId",paperId);
        intent.putExtra("startTime",startTime);
        intent.putExtra("surplusTime",surplusTime);
        intent.putExtra("paperMark1",paperMark1);
        intent.putExtra("paperMark2",paperMark2);
        intent.putExtra("paperMark3",paperMark3);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_similate_answer_card;
    }

    @Override
    protected void initView() {
        setTitleText("答题卡");
        paperId=getIntent().getStringExtra("paperId");
        options=(List<List<String>>) getIntent().getSerializableExtra("options");
        myOptions=(List<List<String>>) getIntent().getSerializableExtra("myOptions");
        paperMark1=getIntent().getIntExtra("paperMark1",0);
        paperMark2=getIntent().getIntExtra("paperMark2",0);
        paperMark3=getIntent().getIntExtra("paperMark3",0);
        startTime=getIntent().getStringExtra("startTime");
        surplusTime=getIntent().getStringExtra("surplusTime");
        rcJduge=findViewById(R.id.rcJduge);
        rcMuti=findViewById(R.id.rcMuti);
        rcSignal=findViewById(R.id.rcSignal);
        tvSubmit=findViewById(R.id.tvSubmit);
        tvMutil=findViewById(R.id.tvMutil);
        tvJudge=findViewById(R.id.tvJudge);
        tvSubmit.setOnClickListener(this::onClick);
        for (int i=0;i<myOptions.size();i++){
            for (int j=0;j<myOptions.get(i).size();j++){
                if (myOptions.get(i).get(j)==null||myOptions.get(i).get(j).equals("")){
                    myOptions.get(i).set(j,"X");
                }
            }
        }


        for (int i=0;i<options.size();i++){
            for (int j=0;j<options.get(i).size();j++){
                if (options.get(i).get(j)==null||options.get(i).get(j).equals("")){
                    options.get(i).set(j,"3");
                }else {
                    editCount++;
                }
                switch (i){
                    case 0:
                        if (options.get(i).get(j).equals("1")){
                            userScore=userScore+paperMark1;
                            correctCount++;
                        }
                        break;
                    case 1:
                        if (options.get(i).get(j).equals("1")){
                            userScore=userScore+paperMark2;
                            correctCount++;
                        }
                        break;
                    case 2:
                        if (options.get(i).get(j).equals("1")){
                            userScore=userScore+paperMark3;
                            correctCount++;
                        }
                        break;
                }
            }
        }


        if (options.get(1).size()>0){
            multAdapter=new SimulateAmswerCardAdapter(options.get(1));
            rcMuti.setLayoutManager(new GridLayoutManager(getContext(),5));
            rcMuti.setAdapter(multAdapter);
            tvMutil.setVisibility(View.VISIBLE);
        }else {
            tvMutil.setVisibility(View.GONE);
        }


        if (options.get(2).size()>0){
            tvJudge.setVisibility(View.VISIBLE);
            judgeAdapter=new SimulateAmswerCardAdapter(options.get(2));
            rcJduge.setLayoutManager(new GridLayoutManager(getContext(),5));
            rcJduge.setAdapter(judgeAdapter);
        }else {
            tvJudge.setVisibility(View.GONE);
        }

        singleAdapter=new SimulateAmswerCardAdapter(options.get(0));
        rcSignal.setAdapter(singleAdapter);
        rcSignal.setLayoutManager(new GridLayoutManager(getContext(),5));


        totalScore=options.get(0).size()*paperMark1+
                options.get(1).size()*paperMark2+
                options.get(2).size()*paperMark3;
        totalCount=options.get(0).size()+options.get(1).size()+options.get(2).size();
    }

    @Override
    protected void initData() {

    }

    public void computePaper(){
        //提交答题结果
        StringBuilder str=new StringBuilder();

        for (int p=0;p<myOptions.size();p++){
            if (myOptions.get(p).size()>0){
                for (int q=0;q<myOptions.get(p).size();q++){
                    if (q==myOptions.get(p).size()-1) {
                        str.append(myOptions.get(p).get(q));
                    }else {
                        str.append(myOptions.get(p).get(q)+",");
                    }
                }
                str.append(";");
            }else {
                str.append("X;");
            }
        }
        submitData(str.toString());
    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvSubmit:
                if (userScore<totalScore*0.6){
                    ExitAnswerProblemDialog1 dialog1=new ExitAnswerProblemDialog1(getContext(),surplusTime, totalCount,totalCount-editCount);
                    dialog1.setClicklistener(new ExitAnswerProblemDialog1.ClickListenerInterface() {
                        @Override
                        public void doSubmit() {
                            computePaper();
                        }
                    });
                    dialog1.show();
                }else {
                    PastTestDialog dialog=new PastTestDialog(this,editCount,correctCount,userScore);
                    dialog.setClicklistener(new PastTestDialog.ClickListenerInterface() {
                        @Override
                        public void doSubmit() {
                            computePaper();
                        }
                    });
                    dialog.show();
                }
                break;
        }
    }


    public void submitData(String strs){
        JSONObject object=new JSONObject();
        try {
            object.put("answerStr",strs);
            object.put("answerTime",startTime);//答题时间
            object.put("id",paperId);//试卷id
            object.put("paperMark",String.valueOf(userScore));//考试分数
            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            object.put("submissionTime",sf.format(System.currentTimeMillis()));//交卷时间
            object.put("trueNum",String.valueOf(correctCount));//答对数
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(this).doPost(UrlConstants.getSubmitTest, "",object, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), PaperResultModel.class);
                        if (obj instanceof PaperResultModel) {
                            PaperResultModel model=(PaperResultModel) obj;
                            ActivityTrainResult.actionStart(getContext(),1,paperId,model);
                            finish();
                        }
                    }else {
                        Toast.makeText(ActivitySimulateAnswerCard.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}
